package cn.yunhe.java.controller;

import cn.hutool.crypto.SecureUtil;
import cn.yunhe.java.object.AjaxDone;
import cn.yunhe.java.object.TableData;
import cn.yunhe.java.pojo.SysRoles;
import cn.yunhe.java.pojo.SysUser;
import cn.yunhe.java.security.user.MyPrincipal;
import cn.yunhe.java.service.SysUserService;
import cn.yunhe.java.utils.DateUtils;
import cn.yunhe.java.vo.UserRoleSetter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("user")
public class SysUserController {

    @Autowired
    private SysUserService service;


    /**
     * 跳转用户列表页面
     */

    @PreAuthorize("hasRole('管理员')")
    @RequestMapping("toList")
    public String toUserList(){
        return "user/list";
    }

    /**
     * 查询列表数据
     */
    @RequestMapping("list")
    @ResponseBody
    public TableData queryByCondition(String loginName,Integer userStatus,int page,int limit){
        TableData td = service.queryByCondition(loginName, userStatus,page,limit);
        return  td;
    }

    /**
     * 到添加用户界面
     * @return
     */
    @RequestMapping("toAdd")
    public String toAdd(){
        return "user/add";
    }

    /**
     * 添加用户信息
     * @return
     */
    @RequestMapping("add")
    @ResponseBody
    public AjaxDone addUser(String username, String loginName,
                            String newPassword, String confirmPassword, String email, HttpServletRequest request){
        if(StringUtils.isEmpty(username)){
            return new AjaxDone(300,"用户名不能为空");
        }

        if(StringUtils.isEmpty(loginName)){
            return new AjaxDone(300,"登录账号不能为空");
        }

        if(StringUtils.isEmpty(newPassword)){
            return new AjaxDone(300,"密码不能为空");
        }

        if(StringUtils.isEmpty(confirmPassword)){
            return new AjaxDone(300,"确认密码不能为空");
        }

        if(!newPassword.equals(confirmPassword)){
            return new AjaxDone(300,"两次密码不一致");
        }

        try {
            SysUser su = new SysUser();
            su.setUserStatus(1);
            su.setLoginName(loginName);
            su.setEmail(email);
            su.setName(username);
            su.setPassword(new BCryptPasswordEncoder().encode(newPassword));
            //SysUser sessionUser = (SysUser) request.getSession().getAttribute("loginUser");

            MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            SysUser sessionUser = principal.getSysUser();

            su.setCreateUser(sessionUser.getName());
            su.setCreateDate(DateUtils.getSystemDate());
            int rst = service.saveUser(su);
            if (rst > 0) {
                return new AjaxDone(200,"添加成功！",null);
            }
        }catch(Exception e){
            e.printStackTrace();
            return new AjaxDone(300,"添加失败！"+e.getMessage(),null);
        }
        return new AjaxDone(300,"服务器繁忙，请稍后重试！",null);
    }

    /**
     * 到编辑页面
     * @return
     */
    @RequestMapping("toEdit")
    public String toEdit(Integer userId, Model model){

        //需要绑定用户的信息到页面
        SysUser su = service.selectByPrimaryKey(userId);
        model.addAttribute("user",su);
        return "user/edit";
    }

    /**
     * 修改用户信息
     * @return
     */
    @RequestMapping("doEdit")
    @ResponseBody
    public AjaxDone doEdit(Integer id,String username, String loginName,
                           String newPassword, String confirmPassword,String email,Integer userStatus){
        if(StringUtils.isEmpty(username)){
            return new AjaxDone(300,"用户名不能为空");
        }

        if(StringUtils.isEmpty(loginName)){
            return new AjaxDone(300,"登录账号不能为空");
        }

        if(StringUtils.isEmpty(newPassword)){
            return new AjaxDone(300,"密码不能为空");
        }

        if(StringUtils.isEmpty(confirmPassword)){
            return new AjaxDone(300,"确认密码不能为空");
        }

        if(!newPassword.equals(confirmPassword)){
            return new AjaxDone(300,"两次密码不一致");
        }
        try{
            SysUser su = new SysUser();
            su.setId(id);
            su.setUserStatus(userStatus);
            su.setLoginName(loginName);
            su.setEmail(email);
            su.setName(username);
            su.setPassword(new BCryptPasswordEncoder().encode(newPassword));
            int rst = service.updateUser(su);
            if(rst>0){
                return new AjaxDone(200, "用户修改成功！", null);
            }
        }catch(Exception e){
            e.printStackTrace();
            return new AjaxDone(300, "修改失败！", null);
        }
        return new AjaxDone(300, "服务器繁忙，请稍后重试！", null);
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @RequestMapping("delete/{id}")
    @ResponseBody
    public AjaxDone deleteUser(@PathVariable("id") Integer userId){
        try{
            int rst = service.delUser(userId);
            if(rst>0){
                return  new AjaxDone(200,"删除成功！");
            }
        }catch(Exception e){
            e.printStackTrace();
            return  new AjaxDone(300,"删除失败！");
        }
        return  new AjaxDone(300,"服务器繁忙，请稍后重试！");
    }

    /**
     * 到设置角色页面
     * @return
     */
    @RequestMapping("toSetRole")
    public String toSetRole(@ModelAttribute("userId") Integer userId, Model model){
        List<SysRoles> rolesList = service.selectAllRoles(userId);
        model.addAttribute("roleList",rolesList);
        return "user/setRole";
    }

    /**
     * 设置角色
     * @return
     */
    @RequestMapping("doSetRole")
    @ResponseBody
    //利用自动封装机制，封装成对象有点小问题
    public AjaxDone doSetRole(Integer userId, @RequestParam("roleIds[]") String [] roleIds, HttpServletRequest request){
        try{
            UserRoleSetter urs = new UserRoleSetter();
            urs.setUserId(userId);
            urs.setRoleIds(Arrays.asList(roleIds));

            //从security的主体中获取用户信息
            MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            SysUser sessionUser = principal.getSysUser();
            int rst = service.doSetRole(urs, sessionUser.getName());
            if(rst>0){
                return  new AjaxDone(200,"设置角色成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return  new AjaxDone(300,"设置角色失败"+e.getMessage());
        }
        return  new AjaxDone(300,"服务器繁忙，请稍后重试！");
    }


    /**
     * 修改用户的状态
     * @param userId
     * @param userStatus
     * @return
     */
    @RequestMapping("updUserStatus")
    @ResponseBody
    public AjaxDone updateUserStatus(Integer userId, Integer userStatus){
       try {
           int rst = service.updateUserStatus(userId, userStatus);
           if (rst > 0) {
               return new AjaxDone(200, "状态修改成功！", null);
           }
       }catch(Exception e){
           //log4j 记录到日志文件
           return new AjaxDone(300,"Error!"+e.getMessage(),null);
       }
       return new AjaxDone(300,"Error!",null);
    }
}
